package com.ettractions.kiosk.services
{
	import com.ettractions.kiosk.events.ImagePreloadServiceEvent;
	import com.ettractions.kiosk.vo.AdVO;
	import com.ettractions.kiosk.vo.BrochureVO;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	import org.robotlegs.mvcs.Actor;

	public class ImagePreloadService extends Actor
	{
		private var _loaderPathMap:Dictionary = new Dictionary(true);
		
		private var _loaderBrochureMap:Dictionary = new Dictionary(true);
		
		private var _loaderAdMap:Dictionary = new Dictionary(true);		
		
		private var _loaderCount:uint = 0;
		
		public function preloadImages(brochures:Vector.<BrochureVO>, ads:Vector.<AdVO>):void
		{
			var loader:Loader;
			
			eventDispatcher.dispatchEvent(new ImagePreloadServiceEvent(ImagePreloadServiceEvent.PRELOAD_IMAGES));
			
			for each (var brochure:BrochureVO in brochures)
			{
				var paths:Vector.<String> = new <String>[
					brochure.media.thumbnailPath,
					brochure.media.contentImagePaths[0]
				];
				
				for each (var path:String in paths)
				{
					loader = new Loader();
					loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoaderComplete);
					loader.load(new URLRequest(path));
					
					_loaderPathMap[loader] = path;
					_loaderBrochureMap[loader] = brochure;
					_loaderCount++;					
				}
			}
			
			for each (var ad:AdVO in ads)
			{
				loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoaderComplete);
				loader.load(new URLRequest(ad.imagePath));
				
				_loaderAdMap[loader] = ad;
				_loaderCount++;					
			}
		}
		
		private function handleLoaderComplete(event:Event):void
		{
			var loaderInfo:LoaderInfo = LoaderInfo(event.target);
			var loader:Loader = loaderInfo.loader;
			var bitmapData:BitmapData = Bitmap(loader.content).bitmapData;
			
			loaderInfo.removeEventListener(Event.COMPLETE, handleLoaderComplete);
			
			if (_loaderBrochureMap[loader])
			{
				var brochure:BrochureVO = _loaderBrochureMap[loader];
				var path:String = _loaderPathMap[loader];
				
				delete _loaderBrochureMap[loader];
				delete _loaderPathMap[loader];

				if (path == brochure.media.thumbnailPath)
					brochure.media.thumbnail = bitmapData;
					
				else
					brochure.media.firstContentImage = bitmapData;
			}
			
			else if (_loaderAdMap[loader])
			{
				var ad:AdVO = _loaderAdMap[loader];
				
				delete _loaderAdMap[loader];
				
				ad.image = bitmapData;
			}
			
			if (--_loaderCount == 0)
				eventDispatcher.dispatchEvent(new ImagePreloadServiceEvent(ImagePreloadServiceEvent.IMAGES_PRELOADED));
		}
	}
}